﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MovieModels;

namespace MK_Movie_Manager
{
    public partial class SearchComponent : UserControl
    {
        MKMovieManager_MainForm MainForm;
        public SearchComponent(MKMovieManager_MainForm mainForm)
        {
            this.MainForm = mainForm;
            InitializeComponent();
        }

        private void btnSearch_Click(object sender, EventArgs e)
        {
            var searchString = this.tb_Search.Text;
            
           // mainform.UpdateStatus("Searching for Movie: " + searchString);

            SearchMovies(searchString);
        }

        private void SearchMovies(string searchString)
        {
            if (!string.IsNullOrWhiteSpace(searchString))
            {
                searchBackgroundWorker.RunWorkerAsync(searchString);
            }
        
        }

        private void btnSelect_Click(object sender, EventArgs e)
        {
            if (this.dgvMovieResult.SelectedRows.Count > 0)
            {
                var value = this.dgvMovieResult.SelectedRows[0];

                MainForm.DisplayMovieDetails(FormatMovieTitle(value.Cells["Title"].Value.ToString()));
            }
        }

        private string FormatMovieTitle(string title)
        {
            return title.Split('-').ElementAt(0).Trim();
        }

        private void searchBackgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            string searchString = Convert.ToString(e.Argument);
            e.Result=BingSearchResult.SearchMoviesByName(searchString);
        }

        private void searchBackgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
           
            var BingSearchResult = e.Result as IList<BingSearchResult>;
            if (BingSearchResult.Any())
            {
                this.dgvMovieResult.DataSource = BingSearchResult;
                this.dgvMovieResult.MultiSelect = false;
                this.dgvMovieResult.Show();
            }
            else
            {
                MessageBox.Show("No Result Found");
            }
        }
    }
}
